package com.ssy.lingxi.purchase.entity.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.ArrayList;
import java.util.List;

/**
* 将自定义的商城ID列表，与表中的Jsonb字段进行转换
* @author wrc
* @date 2021/1/19
*/
@Converter(autoApply = true)
public class JpaJsonToShopIdConverter implements AttributeConverter<List<Long>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<Long> attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"省市区域转换Json错误");
        }
    }

    @Override
    public List<Long> convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new ArrayList<>();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<List<Long>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR,"数据库json字段转换省市区域实体错误");
        }
    }
}
